package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;

public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //1.//检验参数判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "此操作需要登录账号执行");
        }
        //2.查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        // 判断行为实体是否存在
        if (apBehaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该实体行为不存在");
        }
        //判断是否为收藏操作 查询是否已经收藏
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));

        if (dto.getOperation().intValue() == 0) {
            ApCollection apCollection = mongoTemplate.findOne(query, ApCollection.class);
            if (apCollection != null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复收藏");
            }
            //为收藏  修改参数 作者id   tp 时间
            apCollection = new ApCollection();
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setArticleId(dto.getArticleId());
            apCollection.setCollectionTime(new Date());
            apCollection.setType((short) 0);
            mongoTemplate.save(apCollection);
        } else {
            // 取消收藏直接移除
            mongoTemplate.remove(query, ApCollection.class);

        }
        return ResponseResult.okResult();
    }
}
